package com.joe.learn.dubbo.callback.provider;

import com.joe.learn.dubbo.callback.api.CallbackListener;
import com.joe.learn.dubbo.callback.api.CallbackService;
import com.joe.learn.utils.BaseThreadFactory;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;


public class CallbackServiceImpl implements CallbackService {

    private final Map<String, CallbackListener> listeners = new ConcurrentHashMap<String, CallbackListener>();

    public CallbackServiceImpl() {
        BaseThreadFactory threadFactory = new BaseThreadFactory("CallbackService-Thread");
        ExecutorService es = Executors.newCachedThreadPool(threadFactory);
        es.execute(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        TimeUnit.SECONDS.sleep(5);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    try {
                        for (Map.Entry<String, CallbackListener> entry : listeners.entrySet()) {
                            try {
                                entry.getValue().changed(getChanged(entry.getKey()));
                            } catch (Throwable t) {
                                t.printStackTrace();
                            }
                            listeners.remove(entry.getKey());
                        }
                    } catch (Throwable t) { // 防御容错
                        t.printStackTrace();
                    }
                }
            }
        });


    }

    @Override
    public String addListener(String key, CallbackListener listener) {
        if ("1".equals(key)) {
            return getChanged(key);
        } else {
            listeners.put(key, listener);
            return "wait for a minute";
        }
        //listener.changed(getChanged(key)); // 发送变更通知
    }

    private String getChanged(String key) {
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + ":" + key);
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + ":Changed: " + key;
    }

}